/**
 * @file 管理多个 task
 */
import Task from '@/task'
import { EventType, Fn } from '@/index'
class TaskList {
  private taskQueueMap: Map<Fn, Array<Task>> = new Map()
  constructor(public eventType: EventType) {}
  getTaskList = (): Array<Task> => {
    const tempTaskList: Array<Task> = []
    this.taskQueueMap.forEach(taskList => {
      tempTaskList.push(...taskList)
    })
    return tempTaskList
  }
  isExist = (fn: Fn): boolean => {
    return this.taskQueueMap.has(fn)
  }
  addTask = (task: Task) => {
    let taskList = this.taskQueueMap.get(task.fn)
    if (!taskList) {
      this.taskQueueMap.set(task.fn, (taskList = []))
    }
    taskList.push(task)
  }
  getTask = (fn: Fn): Array<Task> => {
    return this.taskQueueMap.get(fn) as Array<Task>
  }
  // 如果 相同类型 相同方法 opt 不同， get, delete 有问题
  deleteTask = (fn: Fn) => {
    const taskList = this.getTask(fn)
    if (!taskList) {
      return
    }
    taskList.forEach(task => {
      task.stopPollApi()
    })
    this.taskQueueMap.delete(fn)
  }
  clear = () => {
    const taskList = this.getTaskList()
    taskList.forEach((task) => {
      // 停止请求
      task.stopPollApi()
    })
    // 重置 taskQueue
    this.taskQueueMap.clear()
  }
}

export default TaskList
